package il.ac.braude.sona.gui.list_table;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JTable;
import javax.swing.SwingUtilities;
/**
 * The ListTable class contains methods to create and controll actions in table
 * 
 * @author  Ofek Ron
 * @author Avihay Avitan
 * @author Nitzan Inbar
 * @author Sasha Rozenthal
 * Laboratory in Software Engineering,Ort Braude College.
 *
 */
public class ListTable<T> extends JTable {
	/**
	 *  all table listeners
	 */
	private ArrayList<ListTableClickListener<T>> listeners = new ArrayList<ListTableClickListener<T>>(); 
	/**
	 * Constructs the ListTable without listeners
	 * @param listModel - the table model
	 */
	public ListTable(ListTableModel<T> listModel ) {
		super(listModel);
		init(listModel);
	}
	/**
	 * Constructs the ListTable with listeners
	 * @param listModel - the table model
	 * @param listener - the table listeners
	 */
	public ListTable(ListTableModel<T> listModel ,ListTableClickListener<T> listener) {
		super(listModel);
		init(listModel);
		addListTableClickListener(listener);
	}
	/**
	 * initiate the listeners and imlement mouse lisitner
	 * @param listModel  - the table model
	 */
	private void init(final ListTableModel<T> listModel) {
		addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent evt) {
				int row = rowAtPoint(evt.getPoint());
				int col = columnAtPoint(evt.getPoint());
				if (row < 0 || col < 0) return;
				if (SwingUtilities.isRightMouseButton(evt)) 
					fireOnRightClick(listModel.get(row));
				else if (evt.getClickCount() >= 2)
					fireOnDoubleClick(listModel.get(row));
				else fireOnClick(listModel.get(row));
					return;
				
				
			}
		});
	}
	
	/**
	 * Adding click lisitner to table model
	 * @param l 
	 */
	public void addListTableClickListener(ListTableClickListener<T> l) {
		if (listeners.contains(l)) return;
		listeners.add(l);
	}
	/**
	 * Notify all lisitners that click preformed
	 * @param t - the clicked row
	 */
	protected void fireOnClick(T t) {
		for (ListTableClickListener<T> l : listeners) 
			l.onClick( t);
	}
	/**
	 * Notify all lisitners that double click preformed
	 * @param t - the clicked row
	 */
	protected void fireOnDoubleClick(T t) {
		for (ListTableClickListener<T> l : listeners) 
			l.onDoubleClick(t);
	}
	/**
	 * Notify all lisitners that right click preformed
	 * @param t - the clicked row
	 */
	protected void fireOnRightClick(T t) {
		for (ListTableClickListener<T> l : listeners) 
			l.onRightClick(t);
	}



	
}
